package cn.xc.org.service.impl;

import cn.xc.basic.service.impl.BaseServiceImpl;
import cn.xc.basic.util.Md5Utils;
import cn.xc.basic.util.StrUtils;
import cn.xc.org.domain.Employee;
import cn.xc.org.mapper.EmployeeMapper;
import cn.xc.org.service.IEmployeeService;
import cn.xc.user.domain.Logininfo;
import cn.xc.user.mapper.LogininfoMapper;
import io.swagger.annotations.Authorization;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void add(Employee employee) {
        //1.处理密码和盐值
        //获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //获取加密之后的密码
        String md5Pwd = Md5Utils.encrypByMd5(employee.getPassword()+salt);
        employee.setPassword(md5Pwd);

        Logininfo logininfo = employee2Logininfo(employee);
        logininfoMapper.save(logininfo);

        //保存員工信息
        employee.setLogininfo_id(logininfo.getId());
        super.add(employee);

        //保存中間表的數據
        employeeMapper.saveEmployeeRole(employee);

    }

    private Logininfo employee2Logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        logininfo.setType(0);
        return logininfo;
    }

    @Override
    public void del(Long id) {
        Employee employee = employeeMapper.loadById(id);
        super.del(id);
        logininfoMapper.remove(employee.getLogininfo_id());

        //刪除中間表的
        employeeMapper.removeEmployeeRoleByEmployeeId(id);
    }

    @Override
    public void update(Employee employee) {
        //1.处理密码和盐值
        //获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //获取加密之后的密码
        String md5Pwd = Md5Utils.encrypByMd5(employee.getPassword()+salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);

        Logininfo logininfo = employee2Logininfo(employee);
        Long logininfo_id = employeeMapper.loadById(employee.getId()).getLogininfo_id();
        logininfo.setId(logininfo_id);

        logininfoMapper.update(logininfo);
        //登录信息id和店铺信息id不能修改
        super.update(employee);

        //删除中间表信息
        employeeMapper.removeEmployeeRoleByEmployeeId(employee.getId());
        //保存新的信息
        employeeMapper.saveEmployeeRole(employee);
    }

}
